package com.shanjupay.common.web;

import com.shanjupay.common.exception.BcException;
import com.shanjupay.common.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Objects;
import java.util.Set;

/**
 * 统一异常处理
 *
 * @author dudu
 */
@Slf4j
public class BaseController {

    @Autowired
    protected HttpServletRequest request;


    /**
     * 拦截对象里面字段校验错误
     * 400 - Bad Request
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @SuppressWarnings("rawtypes")
    public BaseResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String code = Objects.requireNonNull(error).getDefaultMessage();
        return BaseResponse.error(ErrorCode.PARAM_CHECK_ERROR.getCode(), code);
    }

    /**
     * 拦截对象里面字段校验错误
     * 400 - Bad Request
     */
    @ExceptionHandler(BindException.class)
    @SuppressWarnings("rawtypes")
    public BaseResponse handleBindException(BindException e) {
        log.error("参数绑定失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String code = Objects.requireNonNull(error).getDefaultMessage();
        return BaseResponse.error(ErrorCode.PARAM_CHECK_ERROR.getCode(), code);
    }


    /**
     * 405 - Method Not Allowed
     */
    @SuppressWarnings("rawtypes")
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public BaseResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("不支持当前请求方法", e);
        return BaseResponse.error(ErrorCode.METHOD_NOT_ALLOWED_ERROR.getCode(), "不支持当前请求方法");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @SuppressWarnings("rawtypes")
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public BaseResponse handleHttpMediaTypeNotSupportedException(Exception e) {
        log.error("不支持当前媒体类型", e);
        return BaseResponse.error(ErrorCode.MEDIA_TYPE_ERROR.getCode(), "不支持当前媒体类型");

    }

    /**
     * sql错误
     *
     * @param ex UncategorizedSQLException
     * @return 返回
     */
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(UncategorizedSQLException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse handleSqlException(UncategorizedSQLException ex) {
        log.error("SQL执行异常" + ex.toString());
        return BaseResponse.error(ErrorCode.SYSTEM_ERROR.getCode(), "系统异常，请联系管理员");
    }

    /**
     * sql错误
     *
     * @param ex BadSqlGrammarException
     * @return BaseResponse
     */
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse handleSqlException(BadSqlGrammarException ex) {
        ex.printStackTrace();
        log.error("SQL执行异常" + ex.toString());
        return BaseResponse.error(ErrorCode.SYSTEM_ERROR.getCode(), "SQL执行异常");
    }


    /**
     * sql错误
     *
     * @param ex DataIntegrityViolationException
     * @return BaseResponse
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @SuppressWarnings("rawtypes")
    public BaseResponse handleSqlException(DataIntegrityViolationException ex) {
        log.error("数据库字段不能为空" + ex.toString());
        return BaseResponse.error(ErrorCode.SYSTEM_ERROR.getCode(), "系统异常，请联系管理员");
    }


    /**
     * 校验异常
     *
     * @param exception exception
     * @return BaseResponse
     */
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(ValidationException.class)
    public BaseResponse handle(ValidationException exception) {
        String msg = null;
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                //打印验证不通过的信息
                System.out.println(item.getMessage());
                msg = item.getMessage();
            }
        }
        return BaseResponse.error(ErrorCode.PARAM_CHECK_ERROR.getCode(), msg);
    }


    /**
     * json转化异常
     *
     * @param exception exception
     * @return BaseResponse
     */
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public BaseResponse handleJsonException(HttpMessageNotReadableException exception) {
        log.error(exception.getMessage());
        exception.printStackTrace();
        return BaseResponse.error(ErrorCode.PARAM_CHECK_ERROR.getCode(), "参数json格式错误");
    }


    /**
     * io异常
     *
     * @param ex ex
     * @return BaseResponse
     */
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(IOException.class)
    public BaseResponse handleException(IOException ex) {
        log.error("类型转化异常" + ex.toString());
        return BaseResponse.error(ErrorCode.SYSTEM_ERROR.getCode(), "系统异常，请联系管理员");
    }

    /**
     * 自定义异常
     *
     * @param ex ex
     * @return BaseResponse
     */
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(BcException.class)
    public BaseResponse handleException(BcException ex) {
        return BaseResponse.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 统一处理异常堆栈
     *
     * @param e 异常
     * @return 返回系统内部错误
     */
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(Exception.class)
    public BaseResponse handleException(Exception e) {
        //获取详细堆栈信息
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        log.error(sw.toString());
        String msg = e.getMessage();
        if (msg == null) {
            msg = e.toString();
            log.error(msg);
        }
        return BaseResponse.error(ErrorCode.SYSTEM_ERROR.getCode(), "系统异常，请联系管理员");
    }


}
